<template>
  <div class="main">
    <mine-title>前沿算法诊断</mine-title>
    <div class="content">
      <div class="block-header">
        <div class="block-header-left">
          <mine-button type="primary" @click="addModel()"
            ><i class="iconfont icon-add-line"></i>新建前沿算法</mine-button
          >
          <!--          <mine-button type="primary" @click="importModel()"><i class="iconfont icon-upload-line"></i>导入模型</mine-button>-->
          <mine-button
            @click="deleteModel"
            secondary
            :disabled="!multipleSelection.length"
            ><i class="iconfont icon-delete-line"></i>删除</mine-button
          >
          <mine-button type="primary" secondary @click="loadData()"
            ><i class="iconfont icon-reset-line"></i>刷新</mine-button
          >
        </div>
        <div class="block-header-right"></div>
      </div>
      <el-table
        class="table"
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        ref="multipleTable"
      >
        <el-table-column type="selection" width="45"></el-table-column>
        <el-table-column label="序号" show-overflow-tooltip width="60">
          <template slot-scope="scope">
            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }} </span>
          </template>
        </el-table-column>
        <el-table-column
          label="模型名称"
          prop="projectName"
          show-overflow-tooltip
        >
          <template slot="header">
            <span>模型名称</span>
            <mine-table-search
              @searchSubmit="searchSubmit"
              name="projectName"
            ></mine-table-search>
          </template>
        </el-table-column>
        <!--        <el-table-column label="模型类型" show-overflow-tooltip>-->
        <!--          <template slot="header">-->
        <!--            <span>模型类型</span>-->
        <!--            <mine-table-screen @screenSubmit="screenSubmit" name="projectType" :list="classifyList"></mine-table-screen>-->
        <!--          </template>-->
        <!--          <template slot-scope="scope">-->
        <!--            {{ $common.fetchSingleWord({ val: scope.row.projectType, dict: classifyList, flag: "&#45;&#45;" }) }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="模型进度" show-overflow-tooltip>
          <template slot="header">
            <span>模型进度</span>
            <mine-table-screen
              @screenSubmit="screenSubmit"
              name="progressRate"
              :list="progressRate"
            ></mine-table-screen>
          </template>
          <template slot-scope="scope">
            <status-text
              :value="scope.row.progressRate"
              :dict="progressRate"
            ></status-text>
          </template>
        </el-table-column>
        <el-table-column
          label="关联数据集"
          prop="materialSetName"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.materialSetName ? scope.row.materialSetName : "--" }}
          </template>
        </el-table-column>
        <el-table-column label="运行状态" prop="status" show-overflow-tooltip>
          <template slot="header">
            <span>运行状态</span>
            <mine-table-screen
              @screenSubmit="screenSubmit"
              name="status"
              :list="statusList"
            ></mine-table-screen>
          </template>
          <template slot-scope="scope">
            <status-text
              :value="scope.row.status"
              :dict="statusList"
            ></status-text>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <mine-button type="text" @click="check(scope.row)"
              >详情</mine-button
            >
          </template>
        </el-table-column>
      </el-table>
      <mine-pagination
        @numberChange="numberChange"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
      >
      </mine-pagination>
    </div>
  </div>
</template>
<script>
import { mappingMixins } from "./mixins.js";
import statusText from "./components/statusText";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";
import qs from "qs";
export default {
  mixins: [mappingMixins],

  components: { statusText },

  data() {
    return {
      listQuery: {
        status: [],
      },
      tableData: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      multipleSelection: [],
      loading: false,
      typeList: [],
      tableHeight: window.innerHeight - 330,
      timer: null, // 每隔15秒刷新列表数据
    };
  },
  methods: {
    searchSubmit(value) {
      if (value.key === "projectName") {
        this.listQuery.projectName = value.value;
      }
      if (value.key === "materialSetName") {
        this.listQuery.materialSetName = value.value;
      }
      this.loadData(true);
    },
    screenSubmit(value) {
      if (value.key === "projectType") {
        this.listQuery.types = value.value;
      } else if (value.key === "progressRate") {
        this.listQuery.rates = value.value;
      } else if (value.key === "status") {
        this.listQuery.status = value.value;
      }
      this.loadData(true);
    },
    async loadData(flag) {
      if (flag) {
        this.currentPage = 1;
      }
      const params = {
        ...this.listQuery,
        page: this.currentPage,
        pageSize: this.pageSize,
        diagnoseType: 1,
      };
      // this.loading = true;
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/project/search-page",
              RequestMethod: "post",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: params,
              isStringParam: false,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            _self.loading = false;
            if (result.success && res.webInfo.requestId == uuid) {
              const data = result.data;
              _self.tableData = data.list && data.list.length ? data.list : [];
              _self.total = data.rowCount || 0;
            } else {
              _self.tableData = [];
              _self.total = 0;
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/project/search-page",
          "post",
          "application/json;charset=UTF-8",
          params,
          false,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let result = e.data.response;
            // TODO： 定制后台数据处理
            this.loading = false;
            if (result.success) {
              const data = result.data;
              this.tableData = data.list && data.list.length ? data.list : [];
              this.total = data.rowCount || 0;
            } else {
              this.tableData = [];
              this.total = 0;
            }
          },
          {
            once: true,
          }
        );
      } else {
        try {
          const res = await this.$store.dispatch(
            "modelManageProjectSearchPage",
            params
          );
          this.loading = false;
          const result = res.data || {};
          if (result.success) {
            const data = result.data;
            this.tableData = data.list && data.list.length ? data.list : [];
            this.total = data.rowCount || 0;
          } else {
            this.tableData = [];
            this.total = 0;
          }
        } catch (e) {
          console.error(e);
        }
      }
    },
    addModel() {
      this.$router.push({
        path: "/model/addModel",
      });
    },
    importModel() {
      this.$router.push({
        path: "/model/importModel",
      });
    },
    async deleteModel() {
      this.$mineConfirm("确认要删除模型？", "删除提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const ids = this.multipleSelection.map((item) => item.id);
          if (ids.length == 0)
            return this.$message.warning("表格已自动刷新，请重新选择!"); // 定时器表格刷新ids重置提醒
          this.loading = true;
          let res = {};
          let _self = this;
          if (_self.$qwebUtil.isQtClient) {
            const uuid = _self.$qwebUtil.generateRandomUUID();
            let sendObject;
            /* eslint-disable-next-line */
            const channel = new QWebChannel(
              window.qt.webChannelTransport,
              async function (channel) {
                sendObject = channel.objects.sendObject;
                // receivedJSON 修改此处发送请求参数
                const receivedJSON = {
                  RequestUrl: `/project/batch${_self.$qwebUtil.convertIdListToQueryString(
                    ids
                  )}`,
                  RequestMethod: "delete",
                  ContentType: "application/json;charset=UTF-8",
                  RequestBody: {},
                  isStringParam: false,
                  requestId: uuid,
                };
                await send();
                await _self.$qwebUtil.receive(sendObject, receivedJSON);
                // console.error('received','/feCanvas/pageList')
              }
            );
            /* eslint-disable-next-line */
            async function send() {
              sendObject.sendMessage.connect(function (data) {
                if (!data) {
                  console.error("No data received.");
                }
                res = JSON.parse(data);
                const result = res.response || {};
                // update the followings
                if (result.success && res.webInfo.requestId == uuid) {
                  _self.$message.success("删除成功");
                  _self.loadData(true);
                } else {
                  _self.loading = false;
                  _self.$message.error(result.msg || "删除失败");
                }
              });
            }
          } else if (this.$webview2.isWPF) {
            const uuid = this.$webview2.generateRandomUUID();
            console.log(this.$webview2.convertIdListToQueryString(ids));
            await this.$webview2.sendWebView2(
              `/project/batch${this.$webview2.convertIdListToQueryString(ids)}`,
              "delete",
              "application/json;charset=UTF-8",
              {},
              false,
              uuid
            );
            await window.chrome.webview.addEventListener(
              "message",
              (e) => {
                let res = e.data.response;
                console.log(res);
                // TODO： 定制后台数据处理
                if (res.status === 200 && e.data.webInfo.requestId === uuid) {
                  this.$message.success("删除成功");
                  this.loadData(true);
                } else {
                  this.loading = false;
                  this.$message.error(res.msg || "删除失败");
                }
              },
              {
                once: true,
              }
            );
          } else {
            try {
              const res = await this.$store.dispatch(
                "modelManageProjectBatchDelete",
                { idList: ids }
              );
              const result = res.data || {};
              if (result.success) {
                this.$message.success("删除成功");
                this.loadData(true);
              } else {
                this.loading = false;
                this.$message.error(result.msg || "删除失败");
              }
            } catch (e) {
              console.error(e);
            }
          }
        })
        .catch(() => {});
    },
    // 查看详情
    check(val) {
      this.$router.push({
        path: "/model/detail",
        query: {
          id: val.id,
        },
      });
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    numberChange(val) {
      switch (val.flag) {
        case "pageSize":
          this.pageSize = val.pageSize;
          this.loadData(true);
          break;
        case "currentPage":
          this.currentPage = val.currentPage;
          this.loadData(false);
          break;
        default:
          break;
      }
    },
  },
  mounted() {
    this.loadData();
    this.timer = setInterval(() => {
      // 每隔15秒钟执行的操作
      this.loadData();
    }, 15000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
};
</script>

<style lang="less" scoped>
.table {
  margin-top: 15px;
}
</style>
